package com.controller;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.entity.Location;
import com.service.LocationService;
import com.util.LongLatitude;

@Controller
@RequestMapping("/location")
public class LocationController {
	
	@Resource
	LocationService locationService;
	
	/**
	 * 经纬度判断,小于3000km内显示所有相关小区
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/longlatitude", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String longlatitude(ModelMap map, HttpServletRequest request) {
		String longitude = request.getParameter("longitude");
		String latitude = request.getParameter("latitude");
		double thisLongitude = Double.valueOf(longitude.toString());
		double thisLatitude = Double.valueOf(latitude.toString());
		List<Location> list = locationService.selectAll();
		List<Object> location = new ArrayList<Object>();
		for (Location l : list) {
			double d = LongLatitude.Distance(thisLongitude, thisLatitude,
					l.getLongitude(), l.getLatitude());
			if (d < 3000) {
				System.out.println(l.getAddress());
				location.add(l.getAddress());
				continue;
			}
		}
		map.addAttribute("location", location);
		new JSONObject();
		JSONObject json = JSONObject.fromObject(map);
		System.out.println(json);
		return json.toString();
	}

	@RequestMapping(value = "/showlocation")
	public String showlocation(ModelMap map) {
		List<Location> list = locationService.showlocation();
		map.addAttribute("list", list);
		return "location";
	}
	
	@RequestMapping(value="/selectAddress")
	public String selectAddress(ModelMap map){
		List<Location> list = locationService.showlocation();
		map.addAttribute("list", list);
		return "selectAddress";
	}
	
	@RequestMapping(value = "/selectOne")
	public String selectOne(String id, ModelMap map) {
		Location location = locationService.selectOne(id);
		map.addAttribute("location", location);
		return "showlocation";
	}
	
	@RequestMapping(value = "/updatelocation", method = RequestMethod.POST)
	public String updatelocation(Location location) {
		location.setId(location.getId());
		location.setMoeny(location.getMoeny());
		location.setMessagepush(location.getMessagepush());
		int num = locationService.updatelocation(location);
		System.out.println(num);
		return "redirect:/location/showlocation";
	}
}
